package com.efounder.fragment;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.ospmobilelib.R;
import com.efounder.utils.ResStringUtil;
import com.pansoft.resmanager.ResFileManager;
import com.utilcode.util.UriUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Hashtable;
import java.util.List;

/**
 * 用于业务界面加载webview，需在配置文件中配置url
 */
public class WebFragment extends BaseFragment {

    private StubObject mStubObject;
    private View mView;
    private String webUrl;
    private com.pansoft.espcomp.ESPWebView wv;
    //标题栏
    private View viewTitle;
    private TextView tvTitle;
    private String mMenuIconStr;
    private ImageView ivMenuIcon;

    private String directory;
    private Context mContext;

    public WebFragment() {
        // Required empty public constructor
    }

    @SuppressLint("ValidFragment")
    public WebFragment(StubObject object){
        this.mStubObject = object;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView = inflater.inflate(R.layout.fragment_web, container, false);
        //标题栏view
        viewTitle = mView.findViewById(R.id.view_yewu_title);
        tvTitle = (TextView) mView.findViewById(R.id.tv_yewu_frag_name);
        ivMenuIcon = (ImageView) mView.findViewById(R.id.iv_yewu_frag_icon);

        Hashtable menuTable = mStubObject.getStubTable();
        webUrl = (String) menuTable.get("url");
        String param = (String) menuTable.get("param");
        String value = (String) menuTable.get("value");
        if (param != null && value != null) {
            String[] paramStrings = param.split(";");
            String[] valueStrings = value.split(";");
            if (param != null) {
                for (int i = 0; i < paramStrings.length; i++) {
                    if (i == 0)
                        webUrl = webUrl + "?";
                    webUrl = webUrl + paramStrings[i] + "=" + valueStrings[i];
                    if (i != paramStrings.length - 1)
                        webUrl = webUrl + "&";
                }
            }
        }
        wv = (com.pansoft.espcomp.ESPWebView) mView
                .findViewById(R.id.mywebview);
        wv.setWebChromeClient(new WebChromeClient());
		/*
		 * wv.setWebViewClient(new WebViewClient() { public boolean
		 * shouldOverrideUrlLoading(WebView view, String url) { //
		 * 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边 view.loadUrl(url); return
		 * true; } });
		 */
        wv.setWebViewClient(new webClient());
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        wv.setLayoutParams(params1);
        wv.setDownloadListener(new MyWebViewDownLoadListener());

        super.onCreateView(inflater, container, savedInstanceState);
		/*
		 * isPrepared = true; onVisible();
		 */
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //是否配置文件中是否配置了标题与
        if (mStubObject != null) {
            Hashtable stubTable = mStubObject.getStubTable();
            if (stubTable.containsKey("caption")) {
                tvTitle.setText((String) stubTable.get("caption"));
            } else {
                viewTitle.setVisibility(View.GONE);
            }
            if (stubTable.containsKey("menuIcon")) {
                mMenuIconStr = "file://" + ResFileManager.IMAGE_DIR + "/" + (String) stubTable.get("menuIcon");
                LXGlideImageLoader.getInstance().displayImage(getContext(), ivMenuIcon, mMenuIconStr, R.drawable.iframe_icon_refresh, R.drawable.iframe_icon_refresh);
            } else {
                viewTitle.setVisibility(View.GONE);

            }
        }
    }

    private class webClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // dialog.show();
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            LoadingDataUtilBlack.dismiss();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

//            if (null != WebFragment.this.getActivity())
//                LoadingDataUtilBlack.show(WebFragment.this
//                        .getActivity());
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                                       SslError error) {
            handler.proceed();// 接受证书
//            LoadingDataUtilBlack.dismiss();
        }

    }


    @Override
    public void onVisible() {
        // 当单独显示时，取消懒加载
		/*
		 * if (!isAlone && (!isPrepared || !isVisible)) { return; }
		 */
        wv.loadUrl(webUrl);
    }

    //内部类
    private class MyWebViewDownLoadListener implements DownloadListener {


        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
		        	/*if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
		        		Toast t=Toast.makeText(mContext, "需要SD卡。", Toast.LENGTH_LONG);
						t.setGravity(Gravity.CENTER, 0, 0);
						t.show();
						return;
		        	}*/
            directory = ResFileManager.DOWN_LOAD;
            File file = new File(directory);
            if (!file.exists() && !file.isDirectory()) {
                System.out.println("//不存在");
                file.mkdir();
            } else {
                System.out.println("//目录存在");
            }
            DownloaderTask task = new DownloaderTask();
            task.execute(url);
        }

    }

    //内部类
    private class DownloaderTask extends AsyncTask<String, Void, String> {

        public DownloaderTask() {
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stubhttps://3g.zyof.com.cn:1445/msp.do?action=file-view@msp&do=download&url=http://pgoa.zyyt.sinopec.com/zyytpg/dep2715/swgl_2715.nsf/0/482579E80029146348257D6D003BA760/$file/HNX34FJLY8EGD80XAV8A.pdf&encoding=gbk
            String url = params[0];
//					Log.i("tag", "url="+url);
            url = url.substring(0, url.lastIndexOf("&encoding=gbk"));
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            fileName = URLDecoder.decode(fileName);
            Log.i("tag", "fileName=" + fileName);

            //File directory=Environment.getExternalStorageDirectory();
            File file = new File(directory, fileName);
				/*	if(file.exists()){
						Log.i("tag", "The file has already exists.");
						return fileName;
					}*/
            try {
                DefaultHttpClient client = new DefaultHttpClient();
//		                client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
                HttpGet get = new HttpGet(url);


                String cookie = CookieManager.getInstance().getCookie(url);
                get.addHeader("cookie", cookie);
                HttpResponse response = client.execute(get);
                if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                    HttpEntity entity = response.getEntity();
                    InputStream input = entity.getContent();

                    writeToSDCard(fileName, input);

                    input.close();
//							entity.consumeContent();
                    return fileName;
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
//            closeProgressDialog();
            if (result == null) {
                Toast t = Toast.makeText(mContext, ResStringUtil.getString(R.string.common_text_connect_error), Toast.LENGTH_LONG);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
                return;
            }

            Toast t = Toast.makeText(mContext, "已保存到SD卡。", Toast.LENGTH_LONG);
            t.setGravity(Gravity.CENTER, 0, 0);
            t.show();
            //File directory=Environment.getExternalStorageDirectory();
            File file = new File(directory, result);
            Log.i("tag", "Path=" + file.getAbsolutePath());

            try {
                Intent intent = getFileIntent(file);
                if (isIntentAvailable(mContext, intent)) {
                    mContext.startActivity(intent);
                } else {
                    Toast t1 = Toast.makeText(mContext, "请安装该文件类型的程序！", Toast.LENGTH_LONG);
                    t1.setGravity(Gravity.CENTER, 0, 0);
                    t1.show();
                }
            } catch (Exception e) {
                Toast t2 = Toast.makeText(mContext, "该文件打开失败，请检查手机是否存在打开该文件类型的程序。", Toast.LENGTH_LONG);
                t2.setGravity(Gravity.CENTER, 0, 0);
                t2.show();
            }


        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
//            showProgressDialog();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }
    }

    public Intent getFileIntent(File file) {
        //       Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
        Uri uri = UriUtils.getUriForFile(file);
        String type = getMIMEType(file);
        Log.i("tag", "type=" + type);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, type);
        return intent;
    }

    public void writeToSDCard(String fileName, InputStream input) {

        //   if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        // File directory=Environment.getExternalStorageDirectory();
        File file = new File(directory, fileName);
        //          if(file.exists()){
        //              Log.i("tag", "The file has already exists.");
        //              return;
        //          }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            byte[] b = new byte[2048];
            int j = 0;
            while ((j = input.read(b)) != -1) {
                fos.write(b, 0, j);
            }
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
		           /* }else{
		                Log.i("tag", "NO SDCard.");
		            }*/
    }

    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
		          /* 取得扩展名 */
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();

		          /* 依扩展名的类型决定MimeType */
        if (end.equals("pdf")) {
            type = "application/pdf";//
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
                end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
		            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        } else if (end.equals("pptx") || end.equals("ppt")) {
            type = "application/vnd.ms-powerpoint";
        } else if (end.equals("docx") || end.equals("doc")) {
            type = "application/msword";
        } else if (end.equals("xlsx") || end.equals("xls")) {
            type = "application/vnd.ms-excel";
        } else {
            //        /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = "*/*";
        }
        return type;
    }

    /**
     * 判断Intent 是否存在 防止崩溃
     *
     * @param context
     * @param intent
     * @return
     */
    private boolean isIntentAvailable(Context context, Intent intent) {
        final PackageManager packageManager = context.getPackageManager();
        @SuppressLint("WrongConstant") List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        return list.size() > 0;
    }
}
